<template>
  <div>

    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-bottom: 20px">
      <el-breadcrumb-item :to="{ path: '/home' }">{{$t('common.home')}}</el-breadcrumb-item>
      <el-breadcrumb-item>{{$t('common.sys.nav1')}}</el-breadcrumb-item>
      <el-breadcrumb-item>{{$t('common.role')}}</el-breadcrumb-item>
    </el-breadcrumb>

    <div style="padding: 10px 0">
      <el-input style="width:250px" suffix-icon="el-icon-search" :placeholder="$t('common.sys.sysName')" v-model="name" clearable></el-input>
      <el-button style="margin-left: 3px" type="primary" @click="load">{{$t('common.search')}}</el-button>
      <el-button style="margin-left: 3px" type="warning" @click="reset">{{$t('common.reset')}}</el-button>
    </div>
     <div style="margin: 5px 0">
      <el-button type="primary" @click="handleAdd">{{$t('common.add')}}<i class="el-icon-circle-plus-outline"></i></el-button>
    <!--  <el-button type="danger" slot="reference" :disabled="delBtlStatus" @click="deleteBatch(null)">批量删除<i
          class="el-icon-delete"></i>
      </el-button> -->
    </div> 

    <el-table :data="tableData" v-loading="loading" border stripe :header-cell-class-name="headerBg"
      @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" /> -->
      <!-- <el-table-column prop="id" label="ID" width="80" sortable>
      </el-table-column> -->
      <el-table-column prop="name" :label="$t('common.mc')">
      </el-table-column>      
      <el-table-column prop="flag" :label="$t('common.unique')">
      </el-table-column>
      <el-table-column prop="description" :label="$t('common.desc')">
      </el-table-column>
      <el-table-column fixed="right" :label="$t('common.action')" width="280">
        <template #default="scope">
          <el-button type="info" size="small" @click="selectMenu(scope.row)">{{$t('common.setMenu')}}<i class="el-icon-s-tools"></i>
          </el-button>
          <el-button type="warning" size="small" @click="handleEdit(scope.row)">{{$t('common.edit')}}<i class="el-icon-edit"></i>
          </el-button>
          <el-button type="danger" size="small" slot="reference" @click="handleDelete(scope.row.id)">{{$t('common.del')}}<i
              class="el-icon-delete"></i></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="padding-left: 400px;padding-top: 15px">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum"
        :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <!--新增和编辑弹窗-->
    <el-dialog :title="$t('common.roleInfo')" v-model="dialogFormVisible" width="30%">
      <el-form label-width="120px" :model="form" ref="form" :rules="formRlues">
        <el-form-item :label="$t('common.mc')" prop="name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item :label="$t('common.unique')" prop="flag">
          <el-input v-model="form.flag" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item :label="$t('common.desc')" prop="description">
          <el-input v-model="form.description" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">{{$t('common.cancel')}}</el-button>
          <el-button type="primary" @click="save">{{$t('common.ok')}}</el-button>
        </div>
      </template>
    </el-dialog>
    <!--设置菜单弹窗-->
    <el-dialog :title="$t('common.setMenu')" v-model="menuDialogVisible" width="35%" top="20px">
      <el-tree :props="props" :data="menuData" ref="tree" show-checkbox node-key="id" :default-expanded-keys="expends"
        :default-checked-keys="checks">
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <span>
              <component :is="data.icon" style="width: 18px; height: 18px" />{{ node.label }}
            </span>
            <!-- <i :class="data.icon"></i> -->
          </span>
        </template>
      </el-tree>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="menuDialogVisible = false">{{$t('common.cancel')}}</el-button>
          <el-button type="primary" @click="saveRoleMenu">{{$t('common.ok')}}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { useGlobalStore } from "@/stores/globalStore";
export default {
  name: "Role",
  data() {
    let validateRoleName = (rule, value, callback) => {
      if (!value) {
        callback(new Error("角色名不能为空"))
      } else {
        if (value !== "") {
          let item = this.tableData.filter(it=> it.name === value)
          if(item.length >0) callback(new Error('角色名与已有角色名重复!'));
        }        
        callback();
      }
    };
    let validateFlagName = (rule, value, callback) => {
      if (!value) {
        callback(new Error("标识不能为空"))
      } else {
        if (value !== "") {
          let item = this.tableData.filter(it=> it.flag === value)
          if(item.length >0) callback(new Error('标识名与已有标识名重复!'));
        }        
        callback();
      }
    };
    return {
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      name: '',
      description: '',
      form: {},
      formRlues: {
        name: [
          { required: true, validator: validateRoleName, trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入描述', trigger: 'blur' }
        ],
        flag: [
          { required: true, validator: validateFlagName, trigger: 'blur' }
        ]
      },
      multipleSelection: [],
      headerBg: 'headerBg',
      dialogFormVisible: false,
      menuDialogVisible: false,
      menuData: [],
      props: {
        label: 'name',
      },
      expends: [],
      checks: [],
      roleId: 0,
      roleFlag: '',
      delBtlStatus: true,
      loading: false
    }
  },
  //进入页面刷新数据
  created() {
    //请求分页查询数据
    this.load()
  },
   beforeMount() {
    if (window.history && window.history.pushState) {
      history.pushState(null, null, location.href)
      window.addEventListener('popstate', this.goBack)
    }
  },
  beforeUnmount() {
    window.removeEventListener('popstate', this.goBack)
  },

  methods: {
    // 自定返回事件
    goBack() {
      this.$router.go(0)
    },
    //分页查询
    load() {
      this.loading = true
      this.request.get("/role/page", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.name,
        }
      }).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
        this.loading = false
      });
    },
    //页数
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.load()
    },
    //页码
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum
      this.load()
    },
    //搜索重置按钮
    reset() {
      this.name = ""
      this.load()
    },
    //新增
    save() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.request.post("/role", this.form).then(res => {
            if (res.code === 200) {
              ElMessage({
                showClose: true,
                type: "success",
                message: "保存成功",
                duration: 1000
              })
              this.load()
              this.dialogFormVisible = false
            } else {
              ElMessage({
                showClose: true,
                type: "error",
                message: "保存失败",
                duration: 1000
              })
            }
          })
        }
      })
    },
    //打开新增弹窗
    handleAdd() {
      this.dialogFormVisible = true
      this.form = {}
    },
    //编辑
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row))  //深拷贝
      this.dialogFormVisible = true
    },
    //根据ID删除
    handleDelete(id) {
      console.log(id)
      ElMessageBox.confirm(this.$t('common.sureDel'),  this.$t('common.warning'), {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.request.delete("/role/delete/" + id).then(res => {
          if (res.code === 200) {
            ElMessage({
              showClose: true,
              type: "success",
              message: this.$t('common.msgOk'),
              duration: 1000
            })
            this.load()
          } else {
            ElMessage({
              showClose: true,
              type: "error",
              message: this.$t('common.msgErr'),
              duration: 1000
            })
            this.load()
          }
        })
      })
    },
    //批量删除 val:数组
    handleSelectionChange(val) {
      this.multipleSelection = val
      this.delBtlStatus = val.length === 0
    },
    deleteBatch(id) {
      let ids = []
      if (id) {
        ids.push(id)
      } else {
        this.multipleSelection.forEach(row => {
          ids.push(row.id)
        })
      }
      ElMessageBox.confirm(this.$t('common.sureDel'),  this.$t('common.warning'), {
        // confirmButtonText: '确定',
        // cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.request.post("/role/delete/batch", ids).then(res => {
          if (res.code === 200) {
            ElMessage({
              showClose: true,
              type: "success",
              message: "批量删除成功",
              duration: 1000
            })
            this.load()
          } else {
            ElMessage({
              showClose: true,
              type: "error",
              message: "批量删除失败",
              duration: 1000
            })
          }
        })
      })
    },
    //设置菜单
    selectMenu(role) {
      let lang = localStorage.getItem("lang")==="en"? "en": "zhCn"
      this.menuDialogVisible = true
      this.roleId = role.id
      this.roleFlag = role.flag
      //请求菜单数据
      this.request.get("/menu", {
          params: {
            name: "",            
            lang: lang,
          },
        }).then(res => {
        this.menuData = res.data

        //把后台返回的菜单数据处理成 id 数组
        this.expends = this.menuData.map(v => v.id)
      });
      //请求菜单数据
      // this.request.get("/roleMenu/" + this.roleId).then(res => {
      this.request.get("/roleMenu", {
          params: {
            roleId: this.roleId,            
            lang: lang,
          },
        }).then(res => {  
        this.checks = res.data

        this.request.get("/menu/ids").then(r => {
          this.menuDialogVisible = true
          const ids = r.data
          ids.forEach(id => {
            if (!this.checks.includes(id)) {
              this.$refs.tree.setChecked(id, false)
            }
          })
        })
      });
    },
    saveRoleMenu() {
      this.request.post("/roleMenu/" + this.roleId, this.$refs.tree.getCheckedKeys()).then(res => {
        if (res.code === 200) {
          ElMessage({
            showClose: true,
            type: 'success',
            message: '绑定成功',
            duration: 1000
          })
          this.menuDialogVisible = false
          //操作管理员角色后需要重新登录
          if (this.roleFlag === 'ROLE_ADMIN') {
            useGlobalStore().logout()
            // this.$store.commit("logout")
          }
        } else {
          ElMessage({
            showClose: true,
            type: 'error',
            message: '绑定失败',
            duration: 1000
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.headerBg {
  background: #eee !important;
}
</style>